<?php

$this->LoadHelper('MemberHelper');
$MemberHelper = new MemberHelper();

$this->LoadHelper('OrderHelper');
$OrderHelper = new OrderHelper();

$this->LoadHelper('PublicHelper');
$PublicHelper = new PublicHelper();

$this->LoadHelper('MessageHelper');
$MessageHelper = new MessageHelper();

$this->LoadHelper('BankHelper');
$BankHelper = new BankHelper();

$this->LoadHelper('EstimateHelper');
$EstimateHelper = new EstimateHelper();

$member_info = $MemberHelper->getMember($this->UserConfig['Id']);
$this->Assign('member_info', $member_info);

$dp_code = $member_info['u_dpcode'];
$this->LoadResurces('oldapi/class.carloan');
$oldapi = new Carloan();

$sign = $oldapi->sign(array('code' => $dp_code));
$api_baseurl = OLD_SITE_URL.'/OrderDetails/index/?code='.$dp_code.'&sign='.$sign['sign'];
//$base_url = \yii2api\Config::$base_url;
//$uri = 'chedai/online-verify/check-has-result';
if (empty($this->Param['option'])) {
    $member_info = $MemberHelper->getMember($this->UserConfig['Id']);
    //待征信查询列表
    $ajax = $this->Param['ajax'];
    $page = isset($this->Param['page']) ? $this->Param['page'] : 1;
    $rp = isset($this->Param['rp']) ? $this->Param['rp'] : PAGE_SIZE;
    
    if ($ajax) {
        $where = array(
            '`o_status` = ?' => '征信查询'
        );
        $data = $OrderHelper->orderList($where, $page, $rp, $this->Param, $member_info);
        $json_data = array('total' => $data['count'], 'rows' => array());
        
        $mode = Config::GetCommon();
        if (!empty($data['all']))
            foreach ($data['all'] AS $rowNum => $row) {
                //$row['video_audit'] = 0;
                //$model = $this->LoadModel('Public');
                //$vip_cert = $model->getOneRow('order_cert','*',array('`ct_oid` =?' =>$row['o_id'],'`ct_key` =?' =>'vip'));
                //$body = array(
                //    "ct_id" => $vip_cert['ct_id']
                //);
                //$reponse = \Httpful\Request::post($base_url.$uri)->body($body)->sendsType(\Httpful\Mime::FORM)->send();
                //if($reponse->body->code == 200){
                //    $row['video_audit'] = 1;
                //}else{
                //    if($reponse->body->message == '远程面签正在审核，请等待'){
                //        $row['video_audit'] = 1;
                //    }
                //}

                $row['o_sell_time'] = date('Y-m-d H:i:s', $row['o_sell_time']);
                $row['o_search_time'] = date('Y-m-d H:i:s', $row['o_search_time']);
                $row['o_pre_modetext'] = $mode['mode'][$row['o_pre_mode']]['mode_text'];
                $bank_row = $BankHelper->bankRow($row['o_bank_id']);
                $row['o_bank_abb'] = $bank_row['bk_abbreviation'];
                $car_row=$OrderHelper->orderCar($row['o_id']);
                $row['o_count']=$car_row['ot_car_pose'];
                //
                if($row['o_oldsys'] == 1){
                    $sign = $oldapi->sign(array('code' => $dp_code));
                    $row['info_url'] = $api_baseurl.'&id='.$row['o_number'];
                }else{
                    $row['info_url'] = '/index/index/option/info?oid='.$row['o_id'];
                }
                $json_data['rows'][] = $row;
            }
        echo json_encode($json_data);
    } else {
        $this->Assign('member_info', $member_info);
        echo $this->GetView('order_trolist.php');
    }
} else {
    switch($this->Param['option']){
        case 'troinfo':
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            //检测订单是否为权限允许内操作
            $order_check = $OrderHelper->checkOrderper($oid, $this->UserConfig['Id']);
            if(!$order_check['success'])                ErrorMsg::Debug ('无权操作');
            
            $order = $OrderHelper->orderInfo($oid);
            if(empty($order['car']['ot_car_pose']))
                ErrorMsg::Debug('车型构成为空，非法进入！');
            if(!empty($order['attachment'])) foreach($order['attachment'] as $k => $v){
                if(strpos($k, 'url')){
                    $order['attachment']['reurl'][$k] = $v; 
                }else{
                    $order['attachment']['source'][$k] = $v; 
                }
            }
            $back_msg = $this->LoadModel('Public')->getOneRow('order_car', '*', array('`ot_oid` = ?' => $oid));
            $this->Assign('order', $order);
            echo $this->GetView('order_troinfo.php');
            break;
        case 'trosave': //初审单录入
            $save_type = empty($this->Param['savetype']) ? 'draft' : $this->Param['savetype'];
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            //检测订单是否为权限允许内操作
            $order_check = $OrderHelper->checkOrderper($oid, $this->UserConfig['Id']);
            if(!$order_check['success'])                ErrorMsg::Debug ('无权操作');
            $data = array('oid' => $oid, 'uid' => $this->UserConfig['Id']);
            $data['ct_spouse_detail'] = $this->Param['ct_spouse_detail'];
            $data['ct_guarantor_detail'] = $this->Param['ct_guarantor_detail'];
            $data['vip']['ct_idaddress'] = $this->Param['ct_idaddress'];
            $data['vip']['ct_issue'] = $this->Param['ct_issue'];
            $data['vip']['ct_validity_end'] = isset($this->Param['ct_validity_end'])?$this->Param['ct_validity_end']:'0000-00-00';
            $tab_owner = $PublicHelper->getTabFields('order_owner');
            unset($tab_owner[0]);
            foreach($_REQUEST as $k => $v){
                if(substr($k, 0, 3)=='ot_'&&in_array($k, $tab_owner)){
                    $data['owner'][$k] = $v;
                }
            }
            $tab_owner = $PublicHelper->getTabFields('order_car');
            unset($tab_owner[0]);
            foreach($_REQUEST as $k => $v){
                if(substr($k, 0, 3)=='ot_'&&in_array($k, $tab_owner)){
                    $data['car'][$k] = $v;
                }
            }
            $data['car']['ot_loan_limit'] = empty($data['car']['ot_loan_limit']) ? 0 : $data['car']['ot_loan_limit'];
            $tab_owner = $PublicHelper->getTabFields('order_attachment');
            unset($tab_owner[0]);
            foreach($tab_owner as $k=>$v){
                $data['attachment'][$v] = isset($this->Param[$v]) ? $this->Param[$v] : '';
            }
            $data['baseorder'] = array(
                'o_buyer_type' => $this->Param['o_buyer_type'],
                'o_buyer_id' => $this->Param['o_buyer_id'],
                'o_buyer' => $this->Param['o_buyer'],
                'o_business_uid' => $this->UserConfig['Id']
            );
            $data['owner']['ot_liveadd'] = $this->Param['ot_liveadd-province'].' '.$this->Param['ot_liveadd-city'].' '.$this->Param['ot_liveadd-county'].' '.preg_replace('# #','',$this->Param['ot_liveadd-address']);
            $data['owner']['ot_home_add'] = $this->Param['ot_home_add-province'].' '.$this->Param['ot_home_add-city'].' '.$this->Param['ot_home_add-county'].' '.preg_replace('# #','',$this->Param['ot_home_add-address']);
            $data['owner']['ot_company_add'] = $this->Param['ot_company_add-province'].' '.$this->Param['ot_company_add-city'].' '.$this->Param['ot_company_add-county'].' '.preg_replace('# #','',$this->Param['ot_company_add-address']);
            if(isset($data['owner']['ot_contact'])){
                $data['owner']['ot_contact'] = serialize($data['owner']['ot_contact']);
            }
            if(isset($data['car']['ot_calculated'])){                
                $data['car']['ot_bankrt_rate'] = $data['car']['ot_calculated']['bank_rate'] * 100;
                $data['car']['ot_calculated'] = serialize($data['car']['ot_calculated']);
            }
            $order_row = $OrderHelper->orderRow($oid);
            if($order_row['o_status'] != '征信查询' && $save_type != 'draft'){
                ErrorMsg::Debug('当前状态不允许处理');
            }
            //根据贷款金额转换审核模式
            $mode_change = $BankHelper->modeChange($order_row['o_pre_mode'], $data['car']['ot_loan_limit']);
            //根据合同照的图片名排序
            if(!empty($data['attachment']['oa_contract'])){
                $data['attachment']['oa_contract'] = $OrderHelper->sortattachment($data['attachment']['oa_contract'],$oid);
            }

            if($save_type == 'draft'){
                $data['attachment'] = $OrderHelper->attachmentIn($data['attachment'], $mode_change['mode_id'], false, false);
            }else{
                $data['attachment'] = $OrderHelper->attachmentIn($data['attachment'], $mode_change['mode_id'], false, false);
                if(!$data['attachment']){
                    //ErrorMsg::Debug('所需面签资料上传不完全');
                }
            }
            unset($data['attachment']['oa_family']);//家访照
            unset($data['attachment']['oa_sign']);//签字照
            unset($data['attachment']['oa_video']);
            $data['owner']['ot_mobile']=trim($data['owner']['ot_mobile']);
            if(isset($data['ct_spouse_detail'])){
                $data['ct_spouse_detail']['ct_spouse_mobile']=trim($data['ct_spouse_detail']['ct_spouse_mobile']);
            }
            if(isset($data['ct_guarantor_detail'])){
                for($i = 0;$i<count($data['ct_guarantor_detail']);$i++){
                    $data['ct_guarantor_detail'][$i]['ct_guarantor_mobile']=trim($data['ct_guarantor_detail'][$i]['ct_guarantor_mobile']);
                }
            }
            //配偶详细信息转换
            $ct_spouse = empty($data['ct_spouse_detail']) ? array() : $data['ct_spouse_detail'];
            if(!empty($ct_spouse)){
                $data['cert']['spouse'][] = array(
                    'ct_detail' => $ct_spouse,
                    'ct_id' => $ct_spouse['ct_spouse_id']
                );
            }
            $ct_guarantor = empty($data['ct_guarantor_detail']) ? array() : $data['ct_guarantor_detail'];
            if(!empty($ct_guarantor)) foreach($ct_guarantor as $k => $v){
                $data['cert']['guarantor'][] = array(
                    'ct_detail' => $v,
                    'ct_id' => $v['ct_guarantor_id']
                );
            }
            if($save_type == 'draft'){
                $do = $OrderHelper->trialOrderSave($data);
            }else{
                $con_check = $OrderHelper->contactcheck($this->Param['ot_contact'],$oid,$this->Param['ot_mobile']);
                if(!$con_check['success']){
                    ErrorMsg::Debug($con_check['msg']);
                }
                if(NOW_TIME-$this->Param['o_sell_time']>1296000){
                    ErrorMsg::Debug('征信结果过期');
                }
                if($this->Param['ot_liveadd-city'] === '0' || $this->Param['ot_liveadd-county'] === '0'|| $this->Param['ot_liveadd-province'] === '0' || empty($this->Param['ot_liveadd-address'])){
                    ErrorMsg::Debug ('请补充完整邮寄地址');
                }
                if($this->Param['ot_home_add-province'] === '0' || $this->Param['ot_home_add-city'] === '0'|| $this->Param['ot_home_add-county'] === '0' || empty($this->Param['ot_home_add-address'])){
                    ErrorMsg::Debug ('请补充完整住宅地址');
                }
                if($this->Param['ot_company_add-province'] === '0' || $this->Param['ot_company_add-city'] === '0'|| $this->Param['ot_company_add-county'] === '0' || empty($this->Param['ot_company_add-address'])){
                    ErrorMsg::Debug ('请补充完整单位地址');
                }
                if($this->Param['ot_checkin_date'] =='' || $this->Param['ot_checkin_date'] =='0000-00-00' || $this->Param['ot_hiredate'] == '' || $this->Param['ot_hiredate'] == '0000-00-00'){
                    ErrorMsg::Debug ('需填写主贷人入职时间与入住时间');
                }
                if($this->Param['o_bank_id'] == 13 && empty($this->Param['oa_video'])){
                    $model = $this->LoadModel('Public');
                    $vip_cert = $model->getOneRow('order_cert','*',array('`ct_oid` =?' =>$oid,'`ct_key` =?' =>'vip'));
                    $base_url = \yii2api\Config::$base_url;
                    $uri = 'chedai/online-verify/check-has-result';
                    //$header = \yii2api\classes\components\auth\Auth::getHeader();
                    $body = array(
                        "ct_id" => $vip_cert['ct_id']
                    );
                    $reponse = \Httpful\Request::post($base_url.$uri)->body($body)->sendsType(\Httpful\Mime::FORM)->send();
                    if ($reponse->body->code!=200){
                        ErrorMsg::Debug($reponse->body->message);
                    //throw new \ErrorException($reponse->body->message, $reponse->body->code);
                    }else{
                        $video_result = $OrderHelper->videoResult($oid,$reponse->body->data->plat_back->checkUser,$reponse->body->data->plat_back->checkTime,$reponse->body->data->plat_back->urlResult);
                        if(!$video_result['success']){
                            ErrorMsg::Debug('视频审结果保存异常');
                        }
                    }
                }
                $data['car']['o_bank_id'] = $order_row['o_bank_id'];
                $data['car']['oid'] = $oid;
                //贷款利率校验
                $rate_check = $BankHelper->rateCheck($data['car']);                
                if(!$rate_check['success']){
                    ErrorMsg::Debug($rate_check['msg']);
                }
                $data['baseorder']['o_pre_mode'] = $mode_change['mode_id'];
                $do = $OrderHelper->trialOrder($data);
            }
            if($do['success'] == true){
                $log_text = $save_type == 'draft' ? '初审单保存' : '初审录入';
//                if($save_type != 'draft'){
//                    $MessageHelper->sendSingle(array(
//                        'm_uid' => $order_row['o_uid'],
//                        'm_title' => '初审录入成功',
//                        'm_name' => $order_row['o_uname'],
//                        'm_content' => $order_row['o_vip_name'].'初审录入提交成功，等待初审通过',
//                        'm_dateline' => NOW_TIME,
//                        'm_oid' => $oid,
//                        'm_info' => serialize(array('status' => '初审提交', 'code' => $OrderHelper->statusChange('征信查询')))
//                    ));
//                }
                $MemberHelper->saveLog($this->UserConfig, $log_text, json_encode($this->Param), $this->Controller.'_'.$this->Action);
                //20180314
                $OrderHelper->attachCheck($oid);
                ErrorMsg::Debug($save_type == 'draft' ? '保存成功' : '提交成功', TRUE);
            }else{
                ErrorMsg::Debug($do['msg']);
            }
            break;
        case 'trogt'://担保人补录
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $this->Assign('oid', $oid);
            echo $this->GetView('order_trogt.php');
            break;
        case 'trogtsave':
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            //检测订单是否为权限允许内操作
            $order_check = $OrderHelper->checkOrderper($oid, $this->UserConfig['Id']);
            if(!$order_check['success'])                ErrorMsg::Debug ('无权操作');
            $this->Param['uid'] = $this->UserConfig['Id'];
            $result = $OrderHelper->guarantorUp($this->Param);
            if($result['success']){
                $MemberHelper->saveLog($this->UserConfig, '担保人补录', json_encode($this->Param), $this->Controller.'_'.$this->Action);
                ErrorMsg::Debug('保存成功', TRUE);
            }else{
                ErrorMsg::Debug($result['msg']);
            }
            break;
        case 'loanrate':
            $this->LoadHelper('BankHelper');
            $BankHelper = new BankHelper;
            $result = $BankHelper->rateCompute($this->Param);
            if($this->Param['o_bank_id']==15 && $this->Param['ot_car_pose'] == '二手车'){
                $result = $BankHelper->rateNewCompute($this->Param['o_bank_id'], $this->Param['o_bank_name'], $this->Param['ot_loan_type'], $this->Param['ot_loan_year'], $this->Param['ot_reg_province'],
                    $this->Param['ot_car_pose'], $this->Param['ot_car_price'], $this->Param['ot_assessment'], $this->Param['ot_initialrg_time'], $this->Param['ot_car_oprice'],
                    $this->Param['ot_loan_limit'], $this->Param['ot_loan_rate'], $this->Param['ot_service_rate']);
            }
            if($result['success']){
                $mode_attachment = $result['data']['d_mode_info']['attachment'];
                $re_attachment = array();
                if(!empty($mode_attachment)){
                    foreach($mode_attachment as $k => $v){
                        $re_attachment[$v] = $v;
                    }
                }
                $result['data']['d_mode_info']['attachment'] = $re_attachment;
                ErrorMsg::Debug($result['data'], TRUE);
            }else{
                ErrorMsg::Debug($result['msg']);
            }
        case 'testloan':
            $this->LoadHelper('BankHelper');
            $BankHelper = new BankHelper;
            $result = $BankHelper->rateNewCompute(
                $this->Param['bankid'],
                $this->Param['bankname'],
                $this->Param['loanage'],
                $this->Param['province'],
                $this->Param['cartype'],
                $this->Param['carprice'],
                $this->Param['oldprice'],
                $this->Param['otherprice'],
                $this->Param['loanmoney'],
                $this->Param['companyrate'],
                $this->Param['servicerate']
            );
            if($result['success']){
                $mode_attachment = $result['data']['d_mode_info']['attachment'];
                $re_attachment = array();
                if(!empty($mode_attachment)){
                    foreach($mode_attachment as $k => $v){
                        $re_attachment[$v] = $v;
                    }
                }
                $result['data']['d_mode_info']['attachment'] = $re_attachment;
                ErrorMsg::Debug($result['data'], TRUE);
            }else{
                ErrorMsg::Debug($result['msg']);
            }
        case 'exchange': //换配偶做主贷人
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $order_check = $OrderHelper->checkOrderper($oid, $this->Param['uid']);
            if(!$order_check['success'])                ErrorMsg::Debug ('无权操作');
            $result = $OrderHelper->osExchange($oid);
            if($result['success']){
                $MemberHelper->saveLog($this->UserConfig, '换配偶做主贷人', json_encode($this->Param), $this->Controller.'_'.$this->Action);
                ErrorMsg::Debug('处理成功', TRUE);
            }else{
                ErrorMsg::Debug($result['msg']);
            }
            break;
        case 'express':
            $this->LoadHelper('LogisticsHelper');
            $LogisticsHelper = new LogisticsHelper();
            $express = $LogisticsHelper->logisticsAll(array('`ls_status` = ?' => 'no'));
            if(!empty($express)) foreach($express as $k=>$v){
                $order = $OrderHelper->orderRow($v['ls_oid']);
                $express[$k]['ls_uname'] = $order['o_vip_name'];
            }
            $this->Assign('data', $express);
            echo $this->GetView('order_express.php');
            break;
        case 'expsave':
            $this->LoadHelper('LogisticsHelper');
            $LogisticsHelper = new LogisticsHelper();
            $result = $LogisticsHelper->logisticsSave($this->Param);
            if($result['success']){
                $MemberHelper->saveLog($this->UserConfig, '快递单录入', json_encode($this->Param), $this->Controller.'_'.$this->Action);
                ErrorMsg::Debug('处理成功', TRUE);
            }else{
                ErrorMsg::Debug($result['msg']);
            }
            break;
        case 'troremove':
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $order_check = $OrderHelper->checkOrderper($oid, $this->Param['uid']);
            if(!$order_check['success'])                ErrorMsg::Debug ('无权操作');
            $result = $OrderHelper->orderInvalid($oid);
            if($result['success']){
                $MemberHelper->saveLog($this->UserConfig, '作废客户', json_encode($this->Param), $this->Controller.'_'.$this->Action,$oid);
                ErrorMsg::Debug('处理成功', TRUE);
            }else{
                ErrorMsg::Debug($result['msg']);
            }
            break;
        case 'getupatt': //根据贷款金额返回需要上传的附件
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $ot_loan_limit = empty($this->Param['ot_loan_limit']) || !is_numeric($this->Param['ot_loan_limit']) ? ErrorMsg::Debug('贷款金额错误') : $this->Param['ot_loan_limit'];
            $order_row = $OrderHelper->orderRow($oid);
            $mode_attachment = $BankHelper->modeChange($order_row['o_pre_mode'], $ot_loan_limit);
            $re_attachment = array();
            if(!empty($mode_attachment['attachment'])){
                foreach($mode_attachment['attachment'] as $k => $v){
                    $re_attachment[$v] = $v;
                }
            }
            ErrorMsg::Debug($re_attachment, TRUE);
            break;
        case 'guarantor_del': //删除担保人
            $ct_id = empty($this->Param['ct_id']) ? ErrorMsg::Debug('参数错误') : $this->Param['ct_id'];
            $ct_row = $OrderHelper->certRow($ct_id);
            $order_check = $OrderHelper->checkOrderper($ct_row['ct_oid'], $this->Param['uid']);
            if(!$order_check['success'])                ErrorMsg::Debug ('无权操作');
            $do = $OrderHelper->certSave(array('ct_status' => 'del'), array('`ct_key` = ?' => 'guarantor', '`ct_id` = ?' => $ct_id));
            if($do){
                ErrorMsg::Debug('删除成功', TRUE);
            }else{
                ErrorMsg::Debug('删除失败');
            }
            break;
        case 'car'://是否二手车
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $order = $OrderHelper->orderInfo($oid);
            $this->Assign('order', $order);
            echo $this->GetView('order_cargt.php');
            break;
        case 'cardata'://选择二手车信息
            $cc=$this->Param['branch'];
            $bank=$this->Param['bank'];
            $where='已评估';
            $dataarr= $EstimateHelper->estimateAll($bank,$cc,$where);
            $arr=array();
            if(!empty($dataarr['all']))
                foreach ($dataarr['all'] as $k => $v) {
                    $v['et_car_model'] = empty($v['et_car_fullmodel'])? $v['et_car_model']: $v['et_car_model'].'-'.$v['et_car_fullmodel'];
                    $arr[]=array(
                        'text' => $v['et_code'].'-'.$v['et_name'].'-'.$v['et_car_model'].'-'.date("Ymd",$v['et_ftime']).'-'.$v['et_price'],
                        'et_id' => $v['et_id']
                    );
                }
            echo json_encode($arr);
            break;
        case 'carsave':
            $oid = empty($this->Param['oid']) ? ErrorMsg::Debug('参数错误') : $this->Param['oid'];
            $order_row=$this->Param;
            if(empty($order_row['ot_car_pose'])) ErrorMsg::Debug('车型构成不能为空');
            if($order_row['ot_car_pose']=='二手车'){
                if(empty($order_row['et_id']) || !($order_row['et_id'] >0) ) ErrorMsg::Debug('二手车选择不能为空');
            }
            //$oid = empty($this->Param['et_id']) ? ErrorMsg::Debug('缺少车型选择') : $this->Param['oid'];
            $order_check = $OrderHelper->checkOrderper($oid, $this->UserConfig['Id']);
            if(!$order_check['success'])                ErrorMsg::Debug ('无权操作');

            $order_row['uid'] =$this->UserConfig['Id'];
            $do = $OrderHelper->troCarData($order_row);

            if($do['success'] == true){
                $result = $OrderHelper->updateAttachestimate($order_row['oid'],$order_row['et_id']);
                $MemberHelper->saveLog($this->UserConfig, '车型选择', json_encode($this->Param), $this->Controller.'_'.$this->Action.($result>100?'_'.$result:''));
                ErrorMsg::Debug('保存成功', TRUE);
            }else{
                ErrorMsg::Debug($do['msg']);
            }
            break;
        default :
    }
}